package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.qo.JsonResult;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@RequestMapping("role")
@Controller
public class RoleController {

	@Autowired
	private IRoleService roleService;
	@Autowired
	private IPermissionService permissionService;

	@RequestMapping("list")
	public String list(Model model, @ModelAttribute("qo")QueryObject qo){
		PageInfo<Role> pageInfo = roleService.query(qo);
		model.addAttribute("pageInfo",pageInfo);
		return "role/list";
	}
	
	@RequestMapping("input")
	public String input(Long id,Model model){
		List<Permission> permissions = permissionService.list();
		model.addAttribute("permissions", permissions);
		if (id!=null) {
			Role role = roleService.select(id);
			model.addAttribute("role", role);
		}
		return "role/input";
	}
	
	@RequestMapping("delete")
	@ResponseBody
	public JsonResult delete(Long id){
		try {
			if (id!=null) {
				roleService.delete(id);
			}
		return new JsonResult(true,"删除成功");
		}catch (Exception e){
			return new JsonResult(false,"删除失败");
		}
	}
	@RequestMapping("saveOrUpdate")
	@ResponseBody
	public JsonResult saveOrUpdate(Role role, Long[] permissionIds){
		try {
			if (role.getId()!=null) {
				roleService.update(role,permissionIds);
			}else {
				roleService.insert(role,permissionIds);
			}
		return new JsonResult(true,"新增或修改成功");
		}catch (Exception e){
			return new JsonResult(false,"新增或修改失败");
		}
	}
}
